#include <QtGui>
#include "MediaPlayer.h"

VideoWidget::VideoWidget(QWidget* parent):
    QScrollArea(parent)
{
  setAlignment(Qt::AlignCenter);
  m_proc=new QProcess();
  m_proc->setProcessChannelMode(QProcess::MergedChannels);
  connect(m_proc,SIGNAL(readyReadStandardOutput()),this,SLOT(readMessage()));
  m_mode = 0;
  m_fps = 25.0;

  video = new QLabel;
  video->setScaledContents(true);
  setWidget(video);
  setAcceptDrops(true);
}

VideoWidget::~VideoWidget()
{
  stop();
  delete m_proc;
}

void VideoWidget::open(QString& fileName)
{
  stop();
  if(fileName.endsWith(".avi")){
    m_curFile = QDir(fileName).dirName();
    QString common="mplayer -vo gl -slave -quiet -vf screenshot -framedrop -loop 0 -idx -osdlevel 0 -zoom \""+fileName+"\" -wid "+QString::number((int)video->winId());
    m_proc->start(common);
    m_proc->waitForStarted();
    m_mode = 2;

    m_proc->write("pause\n");
    m_proc->write("pausing_keep get_property fps\n");
    m_proc->write("pausing_keep get_time_length\n");
    m_proc->write("pausing_keep get_video_resolution\n");
  }else if(fileName.endsWith(".png")||fileName.endsWith(".jpg")) {
    QPixmap content(fileName);
    m_width = content.width();
    m_height = content.height();
    video->setPixmap(content);
    video->resize(m_width, m_height);
emit sizeChanged(m_width, m_height);
  }
}

void VideoWidget::togglePause()
{
  if(m_proc->state()==QProcess::Running){
    m_proc->write("pause\n");
    if(m_mode == 1)m_mode = 2;
    else m_mode = 1;
  }
}

void VideoWidget::stop()
{
  if(m_proc->state()==QProcess::Running){
    m_proc->kill();
    m_proc->waitForFinished();
  }
}

void VideoWidget::seekTo(double value)
{
  QString tmp;
  value /= m_fps;
  if(m_mode == 2)
    tmp="pausing_keep seek "+QString::number(value)+" 2\n";
  else
    tmp="seek "+QString::number(value)+" 2\n";
  m_pos = value;
  m_proc->write(tmp.toLocal8Bit());
}

void VideoWidget::seek(double value)
{
  QString tmp;
  value /=m_fps;
  if(m_mode == 2)
    tmp="pausing_keep seek "+QString::number(value)+" 0\n";
  else
    tmp="seek "+QString::number(value)+" 0\n";
  m_pos = value;
  m_proc->write(tmp.toLocal8Bit());

}

void VideoWidget::getTimePos()
{
  if(m_mode == 2)
    m_proc->write("pausing_keep get_time_pos\n");
  else
    m_proc->write("get_time_pos\n");
}

void VideoWidget::readMessage()
{
    while(m_proc->canReadLine())
    {
        QString message(m_proc->readLine());
	if(message.startsWith("ANS_fps=")){
	  m_fps=message.mid(8).toDouble();
	}
        else if(message.startsWith("ANS_LENGTH="))
        {
	  m_length=message.mid(11).toDouble();
	  m_length*=m_fps;
	  emit durationChanged(m_length);
        }
        else if(message.startsWith("ANS_TIME_POSITION="))
        {
            m_pos = message.mid(18).toDouble();
	    m_pos *= m_fps;
	    emit posChanged(m_pos);
        }
        else if(message.startsWith("ANS_VIDEO_RESOLUTION="))
        {
            int i = message.indexOf("x");
            int j = message.indexOf("'",i);
            QString tmp=message.mid(22,i-22-1);
            m_width = tmp.toInt();
            QString tmp1 = message.mid(i+1,j-i-1);
            m_height = tmp1.toInt();
            video->resize(m_width, m_height);
            emit sizeChanged(m_width, m_height);
        }
    }
}

void VideoWidget::dragEnterEvent(QDragEnterEvent *event)
 {
     event->acceptProposedAction();
 }

 void VideoWidget::dragMoveEvent(QDragMoveEvent *event)
 {
     event->acceptProposedAction();
 }

 void VideoWidget::dropEvent(QDropEvent *event)
 {
    const QMimeData *mimeData = event->mimeData();

    //QStringList sl = mimeData->formats();
    //QString tt = sl.join(" ");
    //QMessageBox::information(this,"inform",tt);

    QString form = "application/x-qt-windows-mime;value=\"FileName\"";
    QString tmp = QString(mimeData->data(form));
    if(!tmp.isEmpty()){
      emit playFile(tmp);
      event->acceptProposedAction();
      return;
    }

    form = "text/uri-list";
    tmp = QString(mimeData->data(form));
    if(tmp.startsWith("file:///")){
      //tmp = QDir::toNativeSeparators(tmp.mid(8));
      tmp = tmp.left(tmp.size()-2);
       emit playFile(tmp);
      event->acceptProposedAction();
      return;
    }

    form = "application/x-qabstractitemmodeldatalist";
    if(mimeData->hasFormat(form)){
      QByteArray encoded = mimeData->data(form);
      QDataStream stream(&encoded, QIODevice::ReadOnly);
      while(!stream.atEnd()){
	int row,col;
	QMap<int, QVariant> roleDataMap;
	stream >> row >> col >> roleDataMap;
	QString filename,fname = roleDataMap[0].toString();
	if(fname.endsWith(".avi")) filename = "videos/";
	else filename = "images/";
	filename += fname;
	emit playFile(filename);
	event->acceptProposedAction();
	return;
      }
    }
    event->acceptProposedAction();
}

 void VideoWidget::dragLeaveEvent(QDragLeaveEvent *event)
 {
     event->accept();
 }

void VideoWidget::changeSize(int width, int height)
{
    video->resize(width,height);
}

void VideoWidget::shot()
{
  /*QPixmap shotPixmap = QPixmap::grabWindow(video->winId());
  QString fname= (QDateTime::currentDateTime()).toString("MM-dd-yy-hh-mm-ss")+".png";
  fname = QString("images/")+fname;
  shotPixmap.save(fname);*/
  if(m_mode == 2)
    m_proc->write("pausing_keep screenshot 0\n");
  else
    m_proc->write("screenshot 0\n");

  QTimer::singleShot(500,this, SLOT(moveImage()));
}

void VideoWidget::moveImage()
{
  QDir curPath;
  QStringList filters,fileList;
  QString fname="images/";
  QString fname1 = (QDateTime::currentDateTime()).toString("yy-MMdd-hh-mm-ss")+".png";
  fname += fname1;

  filters<<"shot*.png";
  fileList = curPath.entryList(filters);
  if(fileList.size() > 0){
    QFile::copy(fileList.at(0),fname);
    QFile::remove(fileList.at(0));
  }
  emit addImageEntry(fname1, m_curFile, m_pos);
}
